﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using InputBoxSample;
using PatentApp.Models;
using PatentApp.Data;

namespace PatentApp
{
    public partial class dlgCategory : Form
    {
        public dlgCategory()
        {
            InitializeComponent();
            loadData();
        }

        private void loadData()
        {
            using (var session = NHibernateCfg.OpenSession())
                dgvCategory.DataSource = session.CreateCriteria<Kategoria>().List<Kategoria>();  
        }

        private void btnAddCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.OK;
        }

        private void btnAddNext_Click(object sender, EventArgs e)
        {
            InputBoxResult result = InputBox.Show("Nazwa Kategorii:", "Wprowadź wartość", "", new InputBoxValidatingHandler(inputBox_Validating));
            if (result.OK)
            {
                List<Kategoria> lista;
                using (var session = NHibernateCfg.OpenSession())
                    lista = session.CreateCriteria<Kategoria>().List<Kategoria>().ToList<Kategoria>();
                if (lista.Find(x=>x.Nazwa.Equals(result.Text))!=null){
                    MessageBox.Show("Kategoria jest już na liście");
                    return;
                }
                using (var session = NHibernateCfg.OpenSession())
                {
                    var word = new Kategoria
                    {
                        Nazwa = result.Text
                    };
                    session.SaveOrUpdate(word);
                }
                loadData();  
            }
        }

        private void inputBox_Validating(object sender, InputBoxValidatingArgs e)
        {
            if (e.Text.Trim().Length == 0)
            {
                e.Cancel = true;
                e.Message = "Wymagane";
            }
        }
    }
}
